package com.tcs.test.zk.discovery.provider;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tcs.test.zk.discovery.ServiceInfo;
import com.tcs.test.zk.watcher.TreeNodeWatcher;

public class Provider {
	
	private final Logger logger = LoggerFactory.getLogger(Provider.class);
	
	private ServiceInfo serviceInfo;
	
	private CuratorFramework cf = null;
	
	private String ip;

	public Provider(ServiceInfo serviceInfo, CuratorFramework cf, String ip) {
		this.serviceInfo = serviceInfo;
		this.cf = cf;
		this.ip = ip;
	}

	public void start() throws Exception {
		// 根节点路径
		String path = TreeNodeWatcher.ZK_PATH + "/" + serviceInfo.getServiceName();
		Stat stat = cf.checkExists().forPath(path);
		ObjectMapper om = new ObjectMapper();
		logger.info("serviceInfo : {} , byte : {} " , om.writeValueAsString(serviceInfo) , om.writeValueAsString(serviceInfo).getBytes());
		if (stat == null) {
			cf.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path);
		}
//		InetAddress addr = InetAddress.getLocalHost();
//		String ip = addr.getHostAddress().toString();
//		System.out.println("获取本机ip:" + ip);
//		// 但是为了测试，这里不使用本机ip，因为只有一台机器...
//		cf.create().withMode(CreateMode.EPHEMERAL).forPath(path + "/" + ip);
		cf.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path + "/" + om.writeValueAsString(serviceInfo) , om.writeValueAsString(serviceInfo).getBytes());
	}
}